using Microsoft.AspNetCore.Mvc;
using Study1.Common;
using ClassDemo.Services;
using Asp.Versioning;
using ClassDemo.DTO;
using ClassDemo.Model.DTO;
using ClassDemo.Model.Entity;
using ClassDemo.Model.VO;
using ClassDemo.Service;

namespace ClassDemo.Controllers;

/// <summary>
/// 教师管理控制器
/// </summary>
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/teachers")]
[Produces("application/json")]
public class TeacherController : ControllerBase
{
    private readonly ITeacherService _teacherService;
    private readonly IPasswordService _passwordService;

    public TeacherController(ITeacherService teacherService, IPasswordService passwordService)
    {
        _teacherService = teacherService;
        _passwordService = passwordService;
    }

    /// <summary>
    /// 将Teacher实体映射为TeacherVo
    /// </summary>
    /// <param name="teacher">教师实体</param>
    /// <returns>教师VO</returns>
    private TeacherVo MapToTeacherVo(Teacher teacher)
    {
        return new TeacherVo
        {
            Id = teacher.ID,
            Name = teacher.Name,
            Mobile = teacher.Mobile,
            CreateTime = teacher.CreateTime,
            UpdateTime = teacher.UpdateTime
        };
    }

    /// <summary>
    /// 将Teacher实体映射为TeacherCreateResponseVo（创建时使用，不包含敏感信息）
    /// </summary>
    /// <param name="teacher">教师实体</param>
    /// <returns>教师创建响应VO（不包含ID、创建时间、更新时间）</returns>
    private TeacherCreateResponseVo MapToTeacherCreateResponseVo(Teacher teacher)
    {
        return new TeacherCreateResponseVo
        {
            Name = teacher.Name,
            Mobile = teacher.Mobile
        };
    }

    /// <summary>
    /// 获取教师列表
    /// </summary>
    /// <param name="pageIndex">页码</param>
    /// <param name="pageSize">页大小</param>
    /// <param name="keyword">搜索关键词</param>
    /// <param name="mobile">手机号筛选</param>
    /// <param name="name">姓名筛选</param>
    /// <returns>教师列表</returns>
    [HttpGet]
    public async Task<ActionResult<ApiResult<object>>> GetTeachers(
        [FromQuery] int pageIndex = 1,
        [FromQuery] int pageSize = 10,
        [FromQuery] string? keyword = null,
        [FromQuery] string? mobile = null,
        [FromQuery] string? name = null)
    {
        try
        {
            // 如果指定了手机号，直接查找单个教师
            if (!string.IsNullOrEmpty(mobile))
            {
                var teacher = await _teacherService.GetTeacherByMobileAsync(mobile);
                if (teacher == null)
                {
                    return NotFound(ApiResultFactory.DataNotExists("教师不存在"));
                }
                var teacherVo = MapToTeacherVo(teacher);
                return Ok(ApiResultFactory.Success(teacherVo, "获取教师信息成功"));
            }

            // 如果指定了姓名，按姓名搜索
            if (!string.IsNullOrEmpty(name))
            {
                var teachers = await _teacherService.SearchTeachersByNameAsync(name);
                var teacherVos = teachers.Select(MapToTeacherVo).ToList();
                return Ok(ApiResultFactory.Success(teacherVos, "搜索教师成功"));
            }

            // 分页查询
            var (data, total) = await _teacherService.GetTeachersPageAsync(pageIndex, pageSize, keyword);
            var teacherVoList = data.Select(MapToTeacherVo).ToList();
            var pagedResult = PagedResult<TeacherVo>.Create(teacherVoList, total, pageIndex, pageSize);
            return Ok(ApiResultFactory.Success(pagedResult, "获取教师列表成功"));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResultFactory.Fail<object>($"获取教师列表失败：{ex.Message}"));
        }
    }

    /// <summary>
    /// 根据ID获取教师
    /// </summary>
    /// <param name="id">教师ID</param>
    /// <returns>教师信息</returns>
    [HttpGet("{id:int}")]
    public async Task<ActionResult<ApiResult<TeacherVo>>> GetTeacher(int id)
    {
        try
        {
            var teacher = await _teacherService.GetTeacherByIdAsync(id);
            if (teacher == null)
            {
                return NotFound(ApiResultFactory.DataNotExists("教师不存在"));
            }
            var teacherVo = MapToTeacherVo(teacher);
            return Ok(ApiResultFactory.Success(teacherVo, "获取教师信息成功"));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResultFactory.Fail<TeacherVo>($"获取教师信息失败：{ex.Message}"));
        }
    }



    /// <summary>
    /// 创建教师
    /// </summary>
    /// <param name="teacherDto">教师信息</param>
    /// <returns>创建的教师信息</returns>
    [HttpPost]
    public async Task<ActionResult<ApiResult<TeacherCreateResponseVo>>> CreateTeacher([FromBody] TeacherCreateDto teacherDto)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ApiResultFactory.BadRequest("请求参数无效"));
            }

            // 检查手机号是否已存在
            var existingTeacher = await _teacherService.GetTeacherByMobileAsync(teacherDto.Mobile);
            if (existingTeacher != null)
            {
                return Conflict(ApiResultFactory.BadRequest("手机号已存在"));
            }

            // 创建教师对象并加密密码
            var teacher = new Teacher
            {
                Name = teacherDto.Name,
                Mobile = teacherDto.Mobile,
                Password = _passwordService.HashPassword(teacherDto.Password)
            };

            var (success, message) = await _teacherService.AddTeacherAsync(teacher);
            if (success)
            {
                var teacherVo = MapToTeacherCreateResponseVo(teacher);
                return Ok(ApiResultFactory.Success(teacherVo, "创建教师成功"));
            }
            return BadRequest(ApiResultFactory.BadRequest(message));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResultFactory.Fail<TeacherCreateResponseVo>($"创建教师失败：{ex.Message}"));
        }
    }

    /// <summary>
    /// 更新教师信息
    /// </summary>
    /// <param name="id">教师ID</param>
    /// <param name="teacherDto">教师信息</param>
    /// <returns>更新后的教师信息</returns>
    [HttpPut("{id:int}")]
    public async Task<ActionResult<ApiResult<TeacherVo>>> UpdateTeacher(int id, [FromBody] TeacherUpdateDto teacherDto)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ApiResultFactory.BadRequest("请求参数无效"));
            }

            // 获取现有教师信息
            var existingTeacher = await _teacherService.GetTeacherByIdAsync(id);
            if (existingTeacher == null)
            {
                return NotFound(ApiResultFactory.DataNotExists("教师不存在"));
            }

            // 检查手机号是否被其他教师使用
            if (existingTeacher.Mobile != teacherDto.Mobile)
            {
                var teacherWithMobile = await _teacherService.GetTeacherByMobileAsync(teacherDto.Mobile);
                if (teacherWithMobile != null && teacherWithMobile.ID != id)
                {
                    return Conflict(ApiResultFactory.BadRequest("手机号已被其他教师使用"));
                }
            }

            // 更新教师信息
            existingTeacher.Name = teacherDto.Name;
            existingTeacher.Mobile = teacherDto.Mobile;
            
            // 如果提供了新密码，则加密并更新
            if (!string.IsNullOrEmpty(teacherDto.NewPassword))
            {
                existingTeacher.Password = _passwordService.HashPassword(teacherDto.NewPassword);
            }

            var (success, message) = await _teacherService.UpdateTeacherAsync(existingTeacher);
            if (success)
            {
                var teacherVo = MapToTeacherVo(existingTeacher);
                return Ok(ApiResultFactory.Success(teacherVo, "更新教师信息成功"));
            }
            return BadRequest(ApiResultFactory.BadRequest(message));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResultFactory.Fail<TeacherVo>($"更新教师失败：{ex.Message}"));
        }
    }

    /// <summary>
    /// 删除教师
    /// </summary>
    /// <param name="id">教师ID</param>
    /// <returns>操作结果</returns>
    [HttpDelete("{id:int}")]
    public async Task<ActionResult<ApiResult>> DeleteTeacher(int id)
    {
        try
        {
            // 检查教师是否存在
            var existingTeacher = await _teacherService.GetTeacherByIdAsync(id);
            if (existingTeacher == null)
            {
                return NotFound(ApiResultFactory.DataNotExists("教师不存在"));
            }

            var (success, message) = await _teacherService.DeleteTeacherAsync(id);
            if (success)
            {
                return NoContent();
            }
            return BadRequest(ApiResultFactory.BadRequest(message));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResultFactory.Fail($"删除教师失败：{ex.Message}"));
        }
    }

    /// <summary>
    /// 批量删除教师
    /// </summary>
    /// <param name="request">批量删除请求</param>
    /// <returns>操作结果</returns>
    [HttpDelete("batch")]
    public async Task<ActionResult<ApiResult>> DeleteTeachers([FromBody] BatchDeleteRequest request)
    {
        try
        {
            if (!ModelState.IsValid || request?.Ids == null || !request.Ids.Any())
            {
                return BadRequest(ApiResultFactory.BadRequest("请求参数无效"));
            }

            var (success, message) = await _teacherService.DeleteTeachersAsync(request.Ids);
            if (success)
            {
                return Ok(ApiResultFactory.Success(message));
            }
            return BadRequest(ApiResultFactory.BadRequest(message));
        }
        catch (Exception ex)
        {
            return StatusCode(500, ApiResultFactory.Fail($"批量删除教师失败：{ex.Message}"));
        }
    }
}